﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using PsychSurvey.ResearchId;

namespace PsychSurvey.Controls
{
    public partial class LoginControl : System.Web.UI.UserControl
    {
        public delegate void UserLoggedInDelegate(int UserId);
        public event UserLoggedInDelegate UserLoggedIn;
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }
        
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            UserAuthenticate auth = new UserAuthenticate(true);            
            auth.LoginUserCompleted += new PsychSurvey.ResearchId.LoginUserCompletedEventHandler(auth_LoginUserCompleted);
            auth.LoginUserAsync(tbUserName.Text, tbPassword.Text);
        }

        void auth_LoginUserCompleted(object sender, LoginUserCompletedEventArgs e)
        {
            if (e.Result)
            {
                dbDataContext db = new dbDataContext();
                Individual i = db.Individuals.SingleOrDefault(x => x.PPID == e.IndividualId.ToString());
                if (i == null)
                {
                    i = Individual.CreateIndividual(e.IndividualId, tbUserName.Text, db);
                }
                else
                {
                    
                }
                if (UserLoggedIn != null)
                    UserLoggedIn(i.IndividualId);
            }
        }
    }
}